package com.haust.leyou.filter;

import com.haust.leyou.config.FilterProperties;
import com.haust.leyou.config.JwtProperties;
import com.haust.leyou.utils.CookieUtils;
import com.haust.leyou.utils.JwtUtils;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @Auther: csp1999
 * @Date: 2020/12/20/18:13
 * @Description: 登录过滤器
 */
public class LoginFilter extends ZuulFilter {

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private FilterProperties filterProperties;

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 10;
    }

    @Override
    public boolean shouldFilter() {

        // 获取所有白名单路径
        List<String> allowPaths = filterProperties.getAllowPaths();

        // 初始化zuul 网关的运行上下文
        RequestContext context = RequestContext.getCurrentContext();

        // 获取request对象
        HttpServletRequest request = context.getRequest();

        // 获取当前请求路径
        String url = request.getRequestURL().toString();

        // 判断当前请求路径是否在白名单中
        if (allowPaths.contains(url)) {
            // 如果在白名单中就不拦截
            return false;
        }

        // 如果不在白名单中就拦截
        return true;
    }

    /**
     * 完成拦截的业务功能
     *
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {

        // 初始化zuul 网关的运行上下文
        RequestContext context = RequestContext.getCurrentContext();

        // 获取request对象
        HttpServletRequest request = context.getRequest();

        // 从request的cookie中获取token
        String token = CookieUtils.getCookieValue(request, jwtProperties.getCookieName());

        // token判空
//        if(StringUtils.isBlank(token)){
//            // 如果为空则拦截，不放行（不能转发进入）
//            context.setSendZuulResponse(false);
//            // 401 未认证
//            context.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
//        }

        try {
            // 获取token中的用户信息
            JwtUtils.getInfoFromToken(token, jwtProperties.getPublicKey());
        } catch (Exception e) {
            e.printStackTrace();
            // 拦截，不放行（不能转发进入）
            context.setSendZuulResponse(false);
            // 401 未认证
            context.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
        }

        return null;
    }
}
